﻿using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour 
{
    // Objecto publico para ser associado ao player no unity
    public GameObject Player;

    private Vector3 Distance;

    public bool SmoothMouse;

    private float MouseSensivity = 5f;
    private float xRotation;
    private float yRotation;
    public float CurrentXRotation;
    public float CurrentYRotation;
    private float xRotationVelocity;
    private float yRotationVelocity;
    private float MouseSmoothDamp = 0.1f;

    void Start()
    {
        if (PlayerPrefs.GetInt("FPS") == 0)
            Distance = this.transform.position;
        if (PlayerPrefs.GetInt("FPS") == 1)
            Distance = new Vector3(Player.transform.position.x, Player.transform.position.y + 0.5f, Player.transform.position.z);
    }

    void LateUpdate()
    {
        if (PlayerPrefs.GetInt("FPS") == 0)
        {
            this.transform.position = Player.transform.position + Distance;
        }

        if (PlayerPrefs.GetInt("FPS") == 1)
        {
            this.transform.position = Player.transform.position + Distance;
        }
    }

    void Update()
    {
        if (PlayerPrefs.GetInt("FPS") == 1)
        {
            this.transform.position = Player.transform.position + Distance;

            xRotation -= Input.GetAxis("Mouse Y") * MouseSensivity;
            yRotation += Input.GetAxis("Mouse X") * MouseSensivity;

            // Definir rotação vertical maxima para 90 graus para cima e para baixo
            xRotation = Mathf.Clamp(xRotation, -90, 90);

            // Suavizar rotação horizontal
            CurrentXRotation = Mathf.SmoothDamp(CurrentXRotation, xRotation, ref xRotationVelocity, MouseSmoothDamp);

            // Suavizar rotação vertical
            CurrentYRotation = Mathf.SmoothDamp(CurrentYRotation, yRotation, ref yRotationVelocity, MouseSmoothDamp);

            // Se a suavização do rato estiver activada
            if (SmoothMouse == true)
            {
                // Rodar a camera com o rato suavizado
                this.transform.rotation = Quaternion.Euler(CurrentXRotation, CurrentYRotation, 0);
            }

            // OU

            // Se a suavização do rato estiver desactivada
            if (SmoothMouse == false)
            {
                // Rodar a camera com o rato normal
                this.transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
            }
        }
    }
}
